<template>
  <el-dialog
    center
    title="热源权限管理"
    v-model="dialogShow"
    width="30%"
    @close="handleClose"
  >
    <el-tree
      ref="heatSourceTree"
      :data="treeData"
      show-checkbox
      node-key="id"
      :props="defaultProps"
    >
    </el-tree>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSave" v-preventReClick
          >保存</el-button
        >
        <el-button @click="dialogShow = false">取 消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import { toRefs, reactive, onMounted, ref } from "vue";
import { getHourseTree, addHourseTree, getHourseTreePermiss } from "@/api/user";
import { getIds, IterationDelateMenuChildren } from "@/utils/index.js";
import { ElMessage } from "element-plus";
export default {
  props: {
    dialogShow: {
      type: Boolean,
      default: () => {},
    },
    userId: {
      type: String,
      default: () => {},
    },
  },
  setup(props, context) {
    const heatSourceTree = ref(null);
    const state = reactive({
      defaultProps: { children: "children", label: "name" },
      treeData: [],
    });

    onMounted(async () => {
      await getTreeData();
      getChecked();
    });

    const getTreeData = async () => {
      const { data: res } = await getHourseTree();
      if (res.success) {
        state.treeData = res.data;
      }
    };

    /**
     * 获取选中的
     */
    const getChecked = async () => {
      const { data: res } = await getHourseTreePermiss({
        userId: props.userId,
      });
      if (res.success) {
        let list = IterationDelateMenuChildren(res.data);
        let idArr = getIds(list);
        heatSourceTree.value.setCheckedKeys(idArr);
      }
    };

    const handleSave = () => {
      const halfIds = heatSourceTree.value.getHalfCheckedKeys();
      const menuIds = halfIds.concat(heatSourceTree.value.getCheckedKeys());

      addHourseTree({
        userId: props.userId,
        sourceStationId: menuIds.join(","),
      }).then((res) => {
        if (res.data.success) {
          ElMessage.success(res.data.msg);
          handleClose();
        }
      });
    };

    const handleClose = () => {
      context.emit("close", false);
    };
    return {
      ...toRefs(state),
      heatSourceTree,
      handleClose,
      handleSave,
    };
  },
};
</script>
